import { ChangeEvent, useEffect, useState } from 'react'
import styles from './login.module.scss'
import initLoginBg from './init.ts'
import { Input, Space, Button, message } from 'antd'
import './login.less'
import { login} from '@/request/api.ts'
import { useNavigate } from 'react-router-dom';
import { useDispatch } from "react-redux"

const View: React.FC = ()=> {
  useEffect(() => {
    initLoginBg()
    // 自适应效果，窗口大小改变背景大小也跟着改变
    window.onresize = function(){initLoginBg()}
  },[])


  const navigateTo = useNavigate();
  //获取用户输入的用户名
  const [userVal, setUserVal] = useState("")
  const [passwordVal, setPasswordVal] = useState("")
  const dispatch = useDispatch()


  const getUserVal = (e:ChangeEvent<HTMLInputElement>) => setUserVal(e.target.value)
  
  const getPasswordVal = (e:ChangeEvent<HTMLInputElement>) => setPasswordVal(e.target.value)
  
  const loginBtn = async () =>{
    const { code, data } = await login({
      username: userVal,
      password: passwordVal
    })
    if(code == 0){
      dispatch({type: "setUsername",val:data})
      localStorage.setItem('token', data)
      navigateTo("/bookingData")
      message.success("登录成功！")
    } else message.warning( "账号或密码不正确！")
  }

  return (
    <div className={styles.loginPage}>
      {/* {存放背景} */}
      <canvas id="canvas" style={{display: "block"}}></canvas>
      {/* {登录盒子} */}
      <div className={styles.loginBox + " loginbox"}>
        <div className={styles.title}>
          <h1>酒店预定后台管理系统</h1>
          <p>Strive Everyday</p>
        </div>
        <div className="form">
          <Space direction="vertical" size="large" style={{display: 'flex'}}>
            <Input placeholder="用户名" onChange={getUserVal} />
            <Input.Password placeholder="密码" onChange={getPasswordVal} />
            {/* <div className="captchaBox">
              <Input placeholder="验证码" />
              <div className="captchaImg">
                <img height="38" src="https://img0.baidu.com/it/u=741268616,1401664941&fm=253&app=138&size=w931&n=0&f=JPEG&fmt=auto?sec=1698512400&t=cb3415d476ac8977c6bd6a6d364a4bcb" alt="" />
              </div>
            </div> */}
            <div style={{display: 'flex'}}>
              <Button type="primary" className='loginBtn' block onClick={loginBtn}>登录</Button>
              <Button type="primary" className='loginBtn loginBtn2' onClick={() => navigateTo('/official')}>返回首页</Button>
            </div>
          </Space>
        </div>
      </div>
    </div>
  )
}
export default View